#coding=utf-8
from sdsource.models import Stock
from sdsource.web.utility import get_soup
from sdsource.exception import NoIpoError,NoIssuePriceError
from sdsource.web.sina.suggest import query

def get_ipo(code):
    '''上市公司的上市日期'''
    
    def get_ipo_from_soup(soup):
        t = unicode('上市日期：', 'u8')
        
        rq = soup.find(text=lambda x: x.find(t) !=  -1)
        if not rq:
            return None
        
        date = rq.parent.nextSibling.nextSibling.string
        if not date:
            return None
        date = date.encode('u8')
        return date
    
    url = "http://money.finance.sina.com.cn/corp/go.php/vCI_CorpInfo/stockid/%s.phtml"%code
    
    s = get_soup(url)
    date = get_ipo_from_soup(s)
    if not date:
        raise NoIpoError(code, 'sina')
    return date
    
def get_iprice(code):
    '''上市公司的发行价(iprice:issue price)'''
    
    def get_p_from_soup(soup):
        t = unicode('发行价格：', 'u8')
        
        ip = soup.find(text=lambda x: x.find(t) !=  -1)
        if not ip:
            return None
        
        data = ip.parent.nextSibling.nextSibling.string
        if not data:
            return None
        data = data.encode('u8')
        return data
    
    url = "http://money.finance.sina.com.cn/corp/go.php/vCI_CorpInfo/stockid/%s.phtml"%code
    
    s = get_soup(url)
    data = get_p_from_soup(s)
    if not data:
        raise NoIssuePriceError(code, 'sina')
    return data
    
def get_name(code):
    '''上市公司名称'''
    return query(code)[0].name
        
def get_market(code):
    return query(code)[0].market
    
def get_stock(code):
    s = Stock(code)
    s.name = get_name(code)
    s.ipo = get_ipo(code)
    s.market = get_market(code)
    
    try:
        s.iprice = get_iprice(code)
    except NoIssuePriceError, e:
        print e
        s.iprice = None
        
    return s
